package com.dgland.chatgpt.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dgland.chatgpt.pojo.AjaxResult;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@RestController
@RequestMapping(value = "/openai/chatgpt")
public class ChatGptController {

  @RequestMapping(value = "/chat", method = RequestMethod.GET)
  public AjaxResult<String> chat(@RequestBody String prompt) throws Exception {
    /*URL url = new URL("https://api.openai.com/v1/completions");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Authorization", "Bearer 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");
    con.setDoOutput(true);
    String payload = "{\"model\": \"text-davinci-003\",\"prompt\":\"" + prompt + "\",\"max_tokens\":2048,\"temperature\":0.5}";
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
      String inputLine;
      StringBuilder builder = new StringBuilder();
      while ((inputLine = in.readLine()) != null) {
        builder.append(inputLine);
      }
      in.close();
      System.out.println(builder.toString());
      return builder.toString();
    } else {
      return "Error: " + responseCode;
    }*/
   /*CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost request = new HttpPost("https://api.openai.com/v1/completions");
    request.addHeader("Content-Type", "application/json;charset=UTF-8");
    request.addHeader("Authorization", "Bearer " + "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");

    //String payload = "{\"model\": \"text-davinci-003\",\"prompt\":\"" + prompt + "\",\"max_tokens\":1024,\"temperature\":0}";
    String requestJson = String.format(
            "{\n" +
                    "  \"model\": \"text-davinci-003\",\n"+
                    "  \"prompt\":\"%s\",\n"+
                    "  \"temperature\": 0,\n "+
                    "  \"max_tokens\": 2048\n "+
                    "}",prompt
    );
    StringEntity params = new StringEntity(requestJson);
    request.setEntity(params);

    HttpResponse response = httpClient.execute(request);
    String responseString = EntityUtils.toString(response.getEntity());
    System.out.println(responseString);
    JSONObject jsonObject = JSONObject.parseObject(responseString);
    JSONArray choices = jsonObject.getJSONArray("choices");
    String text = new String (choices.getJSONObject(0).getString("text").getBytes(StandardCharsets.UTF_8));
    System.out.println(text);
    return text;*/
    try{
      RestTemplate restTemplate = new RestTemplate();
      HttpHeaders httpHeaders = new HttpHeaders();
      httpHeaders.add("Authorization","Bearer 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");
      httpHeaders.add("Content-Type", "application/json;charset=UTF-8"); // 传递请求体时必须设置
      /**
       * GTP-3语言模型
       * text-davinci-003
       * text-curie-001
       * text-babbage-001
       * text-pippi-001
       * text-ada-001
       * text-neo-001
       */
      Pattern p =  Pattern.compile("\t|\r|\n");
      Matcher m = p.matcher(prompt);
      prompt = m.replaceAll("");
      prompt = prompt.replaceAll(" +", " ");
      String requestJson = String.format(
              "{\n" +
                      "    \"model\": \"text-davinci-003\",\n" +
                      "     \"prompt\": \"%s\",\n" +
                      "      \"temperature\": 0, \n" +
                      "      \"max_tokens\": 2048,\n" +
                      "      \"stream\": false,\n" +
                      "      \"top_p\": 1.0 \n" +
                      "}",prompt
      );

      HttpEntity<String> entity = new HttpEntity<String>(requestJson,httpHeaders);
      ResponseEntity<String> response = restTemplate.exchange("https://api.openai.com/v1/completions", HttpMethod.POST, entity, String.class);

      if(response.getStatusCode().value() == 200){
        System.out.println(response.getBody());
        JSONObject jsonObject = JSONObject.parseObject(response.getBody());
        JSONArray choices = jsonObject.getJSONArray("choices");
        String text = new String (choices.getJSONObject(0).getString("text").getBytes(StandardCharsets.UTF_8));
        return AjaxResult.success("接口访问成功",text);
      }else{
        return AjaxResult.success("接口访问成功","网络错误，我没太听清，请您再说一遍？");
      }
    }catch (Exception e) {
      e.printStackTrace();
      return AjaxResult.error("当前网络通道拥堵，请稍后再试！","");
    }

 }

  @RequestMapping(value = "/chat1", method = RequestMethod.POST)
  public AjaxResult<String> chat1(@RequestBody String prompt) throws Exception {
    try{
      OpenAiService service = new OpenAiService("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",9000);
      CompletionRequest completionRequest = CompletionRequest.builder()
              .prompt(prompt)
              .model("text-davinci-003")
              .temperature(0.1)
              .maxTokens(1024)
              .topP(1.0)
              //.echo(true)
              .build();
      CompletionResult result  = service.createCompletion(completionRequest);
      if(null == result || StringUtils.isEmpty(result.getChoices().get(0).getText())){
        return AjaxResult.success("接口访问成功","网络错误，我没太听清，请您再说一遍？");
      }else{
        return AjaxResult.success("接口访问成功",result.getChoices().get(0).getText());
      }
    }catch (Exception e){
      e.printStackTrace();
      return AjaxResult.error("当前网络通道拥堵，请稍后再试！","");
    }

  }
  

}